/**
 * 问题库
 */
import React, { Component } from "react";
import { connect } from "dva";
import { routerRedux } from "dva/router";
import { Card, Button, Modal, Table, Input, Form, Divider, Switch, message, Icon, Select } from "antd";
import styles from './knowledgeGather.less';
import {
    getGenerateQuestionsList, postGenerateQuestionsDel, postGenerateQuestionsAdd,
    cancelKnowledgeCollect, postGenerateQuestionsEdit, postGenerateAnswers,
} from '@/services/knowledgeGather';
const EditableContext = React.createContext();

const EditableRow = ({ form, index, ...props }) => (
    <EditableContext.Provider value={form}>
        <tr {...props} />
    </EditableContext.Provider>
);

const EditableFormRow = Form.create()(EditableRow);

class EditableCell extends React.Component {
    state = {
        editing: false,
    };

    toggleEdit = () => {
        const editing = !this.state.editing;
        this.setState({ editing }, () => {
            if (editing) {
                this.input.focus();
            }
        });
    };

    save = (e, type) => {
        const { record, handleSave } = this.props;
        this.form.validateFields((error, values) => {
            if (error && error[e.currentTarget.id]) {
                return;
            };
            this.toggleEdit();
            handleSave({ ...record, ...values }, type);
        });
    };

    change = e => {
        const { record, handleSave } = this.props;
        handleSave({ ...record, content: e.target.value });
    }

    renderCell = form => {
        this.form = form;
        const { children, dataIndex, record, title } = this.props;
        const { editing, content } = this.state;

        return editing ? (
            <Form.Item style={{ margin: 0 }}>
                <span style={{ display: 'flex', gap: '12px', alignItems: 'center' }} onBlur={this.toggleEdit}>
                    {form.getFieldDecorator(dataIndex, {
                        rules: [{ required: true, message: `${title} is required.`, }],
                        initialValue: record[dataIndex],
                    })(
                        <Input
                            ref={node => (this.input = node)}
                            onPressEnter={e => this.save(e, 0)}
                            onChange={e => this.change(e)}
                            className={styles.tableInputClass}
                        />
                    )}
                    <span style={{ display: 'flex', gap: '6px' }}>
                        <Icon type="check-circle" theme="filled" onMouseDown={e => { e.preventDefault(); this.save(record[dataIndex], 1) }} style={{ color: '#4fe153', fontSize: '16px' }} />
                        <Icon type="close-circle" theme="filled" onMouseDown={e => { e.preventDefault(); this.save(null, 2) }} style={{ color: 'red', fontSize: '16px' }} />
                    </span>
                </span>
            </Form.Item>
        ) : (
            <div className="editable-cell-value-wrap" style={{ width: 'calc(100% - 47px)', paddingRight: 24, position: 'relative' }} onClick={this.toggleEdit}>
                {children}
                {record.editType ? (
                    <span>
                        <Icon type="check-circle" theme="filled" onMouseDown={e => { e.preventDefault(); this.save(null, 3) }} style={{ color: '#4fe153', fontSize: '16px' }} />
                        <Icon type="close-circle" theme="filled" onMouseDown={e => { e.preventDefault(); this.save(null, 4) }} style={{ color: 'red', fontSize: '16px' }} />
                    </span>
                ) : null}
            </div>
        );
    };

    render() {
        const { editable, dataIndex, title, record, index, handleSave, children, ...restProps } = this.props;

        return (
            <td {...restProps}>{editable ? <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer> : children}</td>
        );
    }
}

class QuestionLibrary extends Component {
    constructor(props) {
        super(props);
        this.state = {
            list: [],
            total: 0,
            queryData: {
                queryString: '',
                current: 1,
                size: 10,
            },
            selectedRowKeys: [],

            questionListData: '',
            addQuestionVisible: false,
            btnAddQuestionLoading: false,

            nextAnswerVisible: false,
            btnNextAnswerLoading: false,
            cancelLoading: false,
        };
        this.columns = [
            {
                title: '标准问',
                dataIndex: 'content',
                key: 'content',
                editable: true,
            },
            {
                title: '操作',
                width: 300,
                align: 'center',
                render: (text, row, index) => {
                    return (
                        <div style={{ display: 'flex', gap: '20px', justifyContent: 'center' }}>
                            <Button type="danger" onClick={() => this.removeQuestion(row.id)} style={{ width: '120px' }}>删除</Button>
                            <Button type="primary" onClick={() => this.similarQuestion(row)} style={{ width: '120px', marginRight: 10 }}>相似问句</Button>
                        </div>
                    );
                },
            },
        ];
    }

    componentDidMount() {
        this.getQuestionList()
    }

    getQuestionList = async () => {
        const { queryData } = this.state;
        let res = await getGenerateQuestionsList(queryData);
        console.log(res);
        this.setState({ list: res.records, total: res.total });
    }

    setQuestionList = value => {
        let { queryData } = this.state;
        queryData.current = 1;
        queryData.queryString = value;
        this.setState({ queryData }, () => this.getQuestionList());
    }

    onSelectChange = selectedRowKeys => {
        console.log('selectedRowKeys changed: ', selectedRowKeys);
        this.setState({ selectedRowKeys });
    };

    changePage = (page, size) => {
        let { queryData } = this.state;
        queryData.current = page;
        queryData.size = size;
        this.setState({ queryData }, () => this.getQuestionList());
    }

    removeQuestion = id => {
        const that = this;
        const { queryData } = this.state;

        Modal.confirm({
            title: '是否确定删除该问题',
            okText: '确定',
            okType: 'danger',
            cancelText: '取消',
            onOk: async () => {
                let res = await postGenerateQuestionsDel({ ids: [id] });
                console.log(res);
                if (res.code === 0) {
                    message.success("操作成功");
                    that.setQuestionList(queryData.queryString);
                }
            },
            onCancel() {
                console.log('取消删除！！！');
            },
        });
    };

    removeQuestionList = () => {
        const that = this;
        const { selectedRowKeys, queryData } = this.state;

        Modal.confirm({
            title: '是否确定删除这些问题',
            okText: '确定',
            okType: 'danger',
            cancelText: '取消',
            onOk: async () => {
                let res = await postGenerateQuestionsDel({ ids: selectedRowKeys });
                console.log(res);
                if (res.code === 0) {
                    message.success("操作成功");
                    that.setState({ selectedRowKeys: [] }, () => that.setQuestionList(queryData.queryString));
                }
            },
            onCancel() {
                console.log('取消删除！！！');
            },
        });
    }

    similarQuestion = row => {
        const { dispatch } = this.props;
        let pathname = "/knowledgeDesign/knowledgeCollect/similarQuestionList";
        dispatch(routerRedux.push({ pathname, query: { questionId: row.id, question: encodeURI(row.content) } }));
    }

    handleSave = (row, type) => {
        const newData = [...this.state.list];
        const index = newData.findIndex(item => row.id === item.id);
        const item = newData[index];
        switch (type) {
            case 0:
                newData.splice(index, 1, { ...item, ...row, editType: true, defalutContent: item.defalutContent ? item.defalutContent : item.content });
                this.setState({ list: newData });
                break;

            case 1:
                this.setState({}, async () => {
                    let obj = { content: item.content, id: item.id, };
                    let res = await postGenerateQuestionsEdit(obj);
                    console.log(res);
                    if (res.code === 0) {
                        newData.splice(index, 1, { ...item, editType: false, defalutContent: undefined });
                        this.setState({ list: newData });
                    }
                });
                break;

            case 2:
                newData.splice(index, 1, { ...item, editType: false, content: item.defalutContent && item.defalutContent != '' ? item.defalutContent : item.content });
                this.setState({ list: newData });
                break;

            case 3:
                this.setState({}, async () => {
                    let obj = { content: item.content, id: item.id, };
                    let res = await postGenerateQuestionsEdit(obj);
                    console.log(res);
                    if (res.code === 0) {
                        newData.splice(index, 1, { ...item, editType: false, defalutContent: undefined });
                        this.setState({ list: newData });
                    }
                });
                break;

            case 4:
                newData.splice(index, 1, { ...item, editType: false, content: item.defalutContent && item.defalutContent != '' ? item.defalutContent : item.content });
                this.setState({ list: newData });
                break;

            default:
                newData.splice(index, 1, { ...item, ...row, editType: true, defalutContent: item.defalutContent ? item.defalutContent : item.content });
                this.setState({ list: newData });
                break;
        };
    };

    render() {
        const { getFieldDecorator, getFieldValue } = this.props.form;
        const {
            list, queryData, total, selectedRowKeys,
            addQuestionVisible, btnAddQuestionLoading,
            nextAnswerVisible, btnNextAnswerLoading,
            cancelLoading,
        } = this.state;
        const components = {
            body: {
                row: EditableFormRow,
                cell: EditableCell,
            },
        };
        const rowSelection = {
            selectedRowKeys,
            onChange: this.onSelectChange,
        };
        const formItemLayout = {
            labelCol: { span: 4 },
            wrapperCol: { span: 19 },
        };
        const columns = this.columns.map(col => {
            if (!col.editable) {
                return col;
            }
            return {
                ...col,
                onCell: record => ({
                    record,
                    editable: col.editable,
                    dataIndex: col.dataIndex,
                    title: col.title,
                    handleSave: this.handleSave,
                }),
            };
        });

        return (
            <div className={styles['question-library']}>
                <Card bordered={false}>
                    <div className={styles.top}>
                        <Button onClick={this.backRouter} loading={cancelLoading}>取消采编</Button>
                        <Button type="primary" onClick={this.nextAnswer}>下一步生成答案</Button>
                    </div>
                    <Divider style={{ margin: '16px 0' }} />
                    <div className={styles.top}>
                        <div>
                            <Input.Search
                                placeholder="搜索问题"
                                onSearch={value => this.setQuestionList(value)}
                                style={{ width: 200 }}
                            />
                        </div>

                        <div style={{ display: 'flex', gap: "20px" }}>
                            <Button type="danger" onClick={this.removeQuestionList}>批量删除</Button>
                            <Button type="primary" onClick={this.addQuestion}>添加问题</Button>
                        </div>
                    </div>
                    <Table
                        components={components}
                        rowKey="id"
                        rowClassName={() => 'editable-row'}
                        bordered
                        columns={columns}
                        dataSource={list}
                        rowSelection={rowSelection}
                        pagination={{
                            current: queryData.current,
                            total: parseInt(total),
                            onChange: this.changePage,
                            showQuickJumper: true,
                            showSizeChanger: true,
                            onShowSizeChange: this.changePage,
                        }}
                    />
                </Card>

                <Modal
                    title={
                        <div>
                            <p style={{ fontWeight: 'bold', marginBottom: 10, fontSize: '18px' }}>添加自定义问题</p>
                            <p style={{ fontSize: '14px', margin: 0, color: '#666666' }}>多个问题请换行，每行为一个单独的标准问，空白、仅符号、仅数字视为无效数据</p>
                        </div>
                    }
                    visible={addQuestionVisible}
                    width={640}
                    centered
                    closable={false}
                    onOk={this.saveAddQuestion}
                    onCancel={this.cancelAddQuestion}
                    footer={[
                        <Button type="danger" onClick={this.cancelAddQuestion}>取消</Button>,
                        <Button type="primary" loading={btnAddQuestionLoading} onClick={this.saveAddQuestion}>添加</Button>,
                    ]}
                >
                    <Input.TextArea
                        rows={10}
                        placeholder="输入问题，多个问题请换行，每行为一个单独的标准问，空白、仅符号、仅数字视为无效数据"
                        value={this.state.questionListData}
                        onChange={this.addQuestionData}
                    />
                </Modal>

                <Modal
                    title={
                        <span style={{ fontWeight: 'bold', fontSize: '18px' }}>根据当前问题生成答案</span>
                    }
                    visible={nextAnswerVisible}
                    width={800}
                    centered
                    closable={false}
                    onOk={this.saveNextAnswer}
                    onCancel={this.cancelNextAnswer}
                    footer={[
                        <Button type="danger" onClick={this.cancelNextAnswer}>取消</Button>,
                        <Button type="primary" loading={btnNextAnswerLoading} onClick={this.saveNextAnswer}>下一步</Button>,
                    ]}
                >
                    <Form {...formItemLayout} className={styles['next-answer']}>
                        <Form.Item label="答案要求">
                            {getFieldDecorator('answerRequirement', {
                                initialValue: (
`准确性：大模型生成的答案必须准确无误。需要深入理解问题，并基于当前文档的数据给出正确的回答。不能有任何误导性或错误的答案。
相关性：生成的答案必须与问题紧密相关。需要识别问题的关键信息，并据此提供有针对性的回答。不能有无关或偏离主题的答案。
完整性：答案应该尽可能完整，涵盖问题的各个方面。并基于当前文档的数据给出全面、细致地回答问题，避免遗漏重要信息。
流畅性：生成的答案在语言表达上应该流畅自然，易于理解。确保答案的通顺性和可读性。
多样性：对于相似问题，应该能够生成多种不同的答案，以满足灵活性和适用性。
安全性：在生成答案的过程中，模型需要遵守相关的安全规定和隐私政策，确保不泄露用户的个人信息或敏感数据。`
                                )
                            })(<Input.TextArea rows={12} maxLength={200} />)}
                        </Form.Item>
                        <Form.Item label="屏蔽词" extra="模型在生成答案时会尽量避免使用屏蔽词，但在必要时也会根据上下文谨慎使用这些词语，以确保回答的准确性和完整性。">
                            {getFieldDecorator('blockingWord')(<Input maxLength={100} />)}
                        </Form.Item>
                        <Form.Item label="免责声明">
                            {getFieldDecorator('disclaimers', {
                                initialValue: '以上答案由模型总结生成，详细信息请参考原文。'
                            })(<Input maxLength={50} />)}
                        </Form.Item>
                        <Form.Item label="答案来源" extra="开启后，知识点中可下载源文件">
                            {getFieldDecorator('answerSource', { valuePropName: 'checked', initialValue: false })(<Switch />)}
                        </Form.Item>
                        <Form.Item label="生成相似问" extra="填写每个问题生成相似问数量">
                            {getFieldDecorator('generateSimilarityQuestion', { valuePropName: 'checked', initialValue: false })(<Switch />)}
                            {getFieldValue('generateSimilarityQuestion') ? (
                                getFieldDecorator('generateSimilarityQuestionCount', { initialValue: 10 })(
                                    <Input style={{ width: '100px', marginLeft: 12 }} />
                                )
                            ) : null}
                        </Form.Item>
                    </Form>
                </Modal>
            </div>
        );
    }

    backRouter = () => {
        Modal.confirm({
            title: '确定取消当前文档的采编',
            okText: '确定',
            okType: 'danger',
            cancelText: '取消',
            onOk: async () => {
                this.setState({ cancelLoading: true })
                let res = await cancelKnowledgeCollect();
                console.log(res);
                if (res.code === 0) {
                    this.setState({ cancelLoading: false })
                    const { dispatch } = this.props;
                    let pathname = "/knowledgeDesign/knowledgeCollect";
                    dispatch(routerRedux.push({ pathname }));
                } else {
                    this.setState({ cancelLoading: false })
                }
            },
            onCancel() {
                console.log('取消操作！！！');
            },
        });
    }




    addQuestion = () => {
        this.setState({ addQuestionVisible: true })
    }

    cancelAddQuestion = () => {
        this.setState({ addQuestionVisible: false, questionListData: '' })
    }

    addQuestionData = e => {
        this.setState({ questionListData: e.target.value })
    }

    saveAddQuestion = async () => {
        const { questionListData, queryData } = this.state;
        let res = await postGenerateQuestionsAdd({ question: questionListData });
        console.log(res);
        if (res.code === 0) {
            message.success('添加成功');
            this.cancelAddQuestion();
            this.setState({ queryData: { ...queryData, current: 1 } }, () => this.getQuestionList());
        } else {
            message.error('添加失败');
            this.cancelAddQuestion();
        }
    }




    nextAnswer = () => {
        this.setState({ nextAnswerVisible: true })
    }

    cancelNextAnswer = () => {
        this.setState({ nextAnswerVisible: false })
    }

    saveNextAnswer = e => {
        e.stopPropagation();
        e.preventDefault();
        const { total } = this.state;
        if(total <= 0) {
            return message.error('当前问题为空，请先添加问题，在生成答案！')
        };
        this.props.form.validateFields(async (err, values) => {
            if (!err) {
                console.log(values);
                let obj = {
                    answerRequirement: values?.answerRequirement,
                    shieldWord: values?.blockingWord,
                    announcement: values?.disclaimers,
                    answerResource: values?.answerSource,
                    generateSimilarQuestion: values?.generateSimilarityQuestion,
                    similarQuestionNumber: values?.generateSimilarityQuestion ? values?.generateSimilarityQuestionCount : undefined,
                };
                let res = await postGenerateAnswers(obj);
                console.log(res);
                if (res.code == 0) {
                    this.cancelNextAnswer();
                    this.nextAnswerRouter();
                }
            }
        })
    }

    nextAnswerRouter = () => {
        const { dispatch } = this.props;
        let pathname = "/knowledgeDesign/knowledgeCollect/generateAnswer";
        dispatch(routerRedux.push({ pathname }));
    }
}

export default connect(({ user }) => ({
    currentUser: user.currentUser,
}))(Form.create()(QuestionLibrary));
